var express = require('express');
var router = express.Router();
const path = require("path");
const fs = require("fs");
const Nedb = require("nedb");
let dbpath = path.join(__dirname, "yandex.db")
let db = new Nedb(
  { filename: dbpath }
);
db.loadDatabase((err) => {
  if (err) {
    console.error("NEDB LOAD ERROR:", err);
  }
})
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get(["/(:name).html", "/(:name).htm"], (req, res) => {
  let name = req.params['name'];
  if (name) {
    db.findOne({ name: name }, function (err, doc) {
      if (err) {
        res.status(500);
        res.send(err);
      } else {
        if (doc) {
          let content = doc['content'];
          res.type("text");
          res.send(content);
        }else{
          res.send(404);
        }

      }
    })
  } else {
    res.send(404);
  }
})

router.get('/add', (req, res) => {
  let name = req.query["name"];
  let content = req.query["content"];
  if (name && content) {
    db.insert({ name, content }, (err, doc) => {
      if (err) {
        res.status(500);
        res.send(err);
      } else {
        res.send("ok");
      }
    })
  } else {
    res.status(400);
    res.send("pls enter valid name and content");
  }
})

module.exports = router;
